import React, { useEffect, useRef } from 'react';
import { Button } from 'antd';
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import '@xterm/xterm/css/xterm.css';
import './CommandOutputComponent.css';

import cleanOutputIcon from '../../../assets/svgs/clean-output-icon.svg';
import hideOutputIcon from '../../../assets/svgs/hide-output-icon.svg';

interface CommandOutputComponentProps {
  output: string[];
  onHideOutput: () => void;
}

const CommandOutputComponent: React.FC<CommandOutputComponentProps> = ({
  output,
  onHideOutput,
}) => {
  const terminalRef = useRef<HTMLDivElement>(null);
  const termRef = useRef<Terminal | undefined>();
  const fitAddonRef = useRef<FitAddon | undefined>();
  const resizeObserverRef = useRef<ResizeObserver | null>(null);

  useEffect(() => {
    const term = new Terminal({
      fontSize: 14,
      fontFamily: 'monospace',
      theme: {
        background: '#fff',
        foreground: '#000',
        cursor: '#000',
        selectionBackground: '#eee',
      },
      cursorBlink: false,
      scrollback: 1000,
      disableStdin: true,
    });

    const fitAddon = new FitAddon();
    term.loadAddon(fitAddon);
    termRef.current = term;
    fitAddonRef.current = fitAddon;

    if (terminalRef.current) {
      term.open(terminalRef.current);

      // 使用 ResizeObserver 安全适配 terminal 容器
      const resizeObserver = new ResizeObserver(() => {
        try {
          fitAddon.fit();
        } catch (err) {
          console.warn('FitAddon failed to fit terminal:', err);
        }
      });

      resizeObserver.observe(terminalRef.current);
      resizeObserverRef.current = resizeObserver;
    }

    window.addEventListener('resize', handleWindowResize);

    return () => {
      term.dispose();
      window.removeEventListener('resize', handleWindowResize);
      resizeObserverRef.current?.disconnect();
    };
  }, []);

  const handleWindowResize = () => {
    try {
      fitAddonRef.current?.fit();
    } catch (e) {
      console.warn('Window resize fit error:', e);
    }
  };

  useEffect(() => {
    const term = termRef.current;
    if (term) {
      term.clear();
      term.write(output.join('\n') + '\n');
    }
  }, [output]);

  return (
    <div className="output-container">
      <div className="output-border-container">
        <div className="button-container">
          <Button
            size="small"
            onClick={() => termRef.current?.clear()}
            title="清除输出"
          >
            <img src={cleanOutputIcon} width={16} height={16} alt="清除输出" />
          </Button>
          <Button size="small" onClick={onHideOutput} title="隐藏输出">
            <img src={hideOutputIcon} width={16} height={16} alt="隐藏输出" />
          </Button>
        </div>
        <div ref={terminalRef} className="output-terminal" />
      </div>
    </div>
  );
};

export default CommandOutputComponent;
